package com.zhoutao.blog.seven.api;


import com.zhoutao.blog.seven.model.Response;
import com.zhoutao.blog.seven.model.exception.LimitOperatorException;
import com.zhoutao.blog.seven.model.response.Comment;
import com.zhoutao.blog.seven.service.CommonService;
import com.zhoutao.blog.seven.utils.TimeParseUtils;
import com.zhoutao.blog.seven.utils.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/api/comment")
public class CommentApiController {

    @Autowired
    private HttpSession session;

    @Autowired
    private CommonService commentService;

    @PostMapping
    public Response<String> saveComment(@RequestBody Comment comment) {
        final LocalDateTime lastComment = TimeParseUtils.parse((Long) session.getAttribute("lastComment"));
        Long diff = TimeUtils.diff(lastComment, LocalDateTime.now());
        if (diff < 10_000) {
            throw new LimitOperatorException("操作频率过快，请稍后再试");
        }

        this.commentService.save(comment);
        return Response.success("OK");
    }
}
